﻿/*
 * Load dữ liệu từ các bảng
 * 1. Catalogue_Department
 * 2. Training_Subject
 * 
 * Lưu dữ liệu vào bảng
 * 1. Training_Subject
 * 
 * Version: 0.0.0.1
*/
using System;
using DevExpress.XtraEditors;
using UniMana.Utils.Data;
using UniMana.Utils.Helper;
using UniMana.Data;
using UniMana.Utils.Controls;
using System.Windows.Forms;
using DevExpress.XtraBars;
using System.Data.Linq;

namespace UniMana.Win.Training
{
    public partial class FrmSubject : DevExpress.XtraEditors.XtraForm
    {
        private DBMain m_catalogue = new DBMain();
        private DBMain m_dbTraining = new DBMain();
        private bds m_bds = new bds();
        private int m_iAction;
        private const int ACTION_EDIT = 2;
        private const int ACTION_NEW = 1;
        private const int ACTION_NO = 0;
        public FrmSubject()
        {
            if (!UniMana.Data.SysUtils.CheckAccessByRule("R021"))
            {
                XtraMessageBox.Show("Bạn không có quyền này");
                return;
            }

            //this.xucBar.AddNewVisible = Lib.Sys.Utils.CheckAddByRule(Utils.Config.RuleConfig.SUBJECT);
            //this.xucBar.EditVisible = Lib.Sys.Utils.CheckEditByRule(Utils.Config.RuleConfig.SUBJECT);
            //this.xucBar.DeleteVisible = Lib.Sys.Utils.CheckDeleteByRule(Utils.Config.RuleConfig.SUBJECT);
            //this.xucBar.ExportExcelVisible = Lib.Sys.Utils.CheckExportByRule(Utils.Config.RuleConfig.SUBJECT);
            //this.xucBar.ImportExcelVisible = Lib.Sys.Utils.CheckImportByRule(Utils.Config.RuleConfig.SUBJECT);

            InitializeComponent();
            InitControlEvent();
            LoadData();
        }
        private void LoadData()
        {
            //DataTable dt = m_catalogue.m_DCReadOnly.Catalogue_Departments.ConvertToTable(
            lueCatalogue_DepartmentNB.GetData(m_catalogue.m_DCReadOnly.Catalogue_Departments.GetDepartmentSubjectManage(), "Catalogue_DepartmentKey","Name");
        }
        public void InitControlEvent()
        {

            xucBar.btnAddNew_Click += new UniMana.Utils.Controls.xucBar.ButtonClickHandler(this.btnAddNew_Click);
            xucBar.btnDelete_Click += new UniMana.Utils.Controls.xucBar.ButtonClickHandler(this.btnDelete_Click);
            xucBar.btnSave_Click += new UniMana.Utils.Controls.xucBar.ButtonClickHandler(this.btnSave_Click);
            xucBar.btnEdit_Click += new UniMana.Utils.Controls.xucBar.ButtonClickHandler(this.btnEdit_Click);
            xucBar.btnCancel_Click += new UniMana.Utils.Controls.xucBar.ButtonClickHandler(this.btnCancel_Click);
            xucBar.btnExport_Click += new UniMana.Utils.Controls.xucBar.ButtonClickHandler(this.btnExport_Click);
            xucBar.btnRefresh_Click += new UniMana.Utils.Controls.xucBar.ButtonClickHandler(this.btnRefresh_Click);
        }
        private void btnRefresh_Click(object sender, ItemClickEventArgs e)
        {
            GetSubject();
        }
        private void btnAddNew_Click(object sender, ItemClickEventArgs e)
        {
            if (!UniMana.Data.SysUtils.CheckAddByRule("R021"))
            {
                XtraMessageBox.Show("Bạn không có quyền này");
                return;
            }
            this.m_iAction = ACTION_NEW;
            this.txtID.DataBindings.Clear();
            this.txtName.DataBindings.Clear();
            this.txtNote.DataBindings.Clear();
            this.Edit_AddNew();
        }
        private void btnCancel_Click(object sender, ItemClickEventArgs e)
        {
            Finish();
        }
        private void btnEdit_Click(object sender, ItemClickEventArgs e)
        {
            if (!UniMana.Data.SysUtils.CheckEditByRule("R021"))
            {
                XtraMessageBox.Show("Bạn không có quyền này");
                return;
            }
            this.Edit_AddNew();
            this.m_iAction = ACTION_EDIT;
        }
        private void btnDelete_Click(object sender, ItemClickEventArgs e)
        {
            if (!UniMana.Data.SysUtils.CheckDeleteByRule("R021"))
            {
                XtraMessageBox.Show("Bạn không có quyền này");
                return;
            }
            if (this.m_bds.Count > 0)
            {
                DialogResult dialogResult = this.ShowConfirm();
                if (dialogResult == DialogResult.Yes)
                {
                    int subJectKey = (int)grvSubject.GetFocusedRowCellValue(gclTraining_SubjectKey);
                    if (CheckBeforDelete.Check("Training_Subject","Training_SubjectKey", subJectKey))
                    {
                        m_bds.DeleteCurrent();
                        this.Save(m_bds, m_dbTraining.m_DCSave);
                        
                    }
                    else
                    {
                        XtraMessageBox.Show("Bạn không được xóa dữ liệu này.");
                    }
                }
            }
            else
            {
                XtraMessageBox.Show("Không thể xóa khi không có dữ liệu.");
            }
        }
        private void btnExport_Click(object sender, ItemClickEventArgs e)
        {
            if (!UniMana.Data.SysUtils.CheckExportByRule("R021"))
            {
                XtraMessageBox.Show("Bạn không có quyền này");
                return;
            }
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "*.xlsx | *.xls";
            sfd.Title = "Lưu tập tin excel 2007";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                this.gclCredits1.Visible = true;
                this.gclCredits2.Visible = true;
                this.gclCredits3.Visible = true;
                this.gclCredits4.Visible = true;
                this.gclTotalCredits.Visible = true;
                this.gclNote.Visible = true;

                this.grvSubject.ExportToXlsx(sfd.FileName);

                this.gclCredits1.Visible = false;
                this.gclCredits2.Visible = false;
                this.gclCredits3.Visible = false;
                this.gclCredits4.Visible = false;
                this.gclTotalCredits.Visible = false;
                this.gclNote.Visible = false;

            }
        }
        private void btnSave_Click(object sender, ItemClickEventArgs e)
        {
            SaveData();
        }
        private void SaveData()
        {
            bool succ = false;
            int departmentKey = this.lueCatalogue_DepartmentNB.GetIntValue();

            int SubjectKey = this.grvSubject.GetFocusedRowCellValue(this.gclTraining_SubjectKey).ToInt();
            string subjectID = this.txtID.Text;
            string subjectname = this.txtName.Text;
            string subjectNote = this.txtNote.Text;
            double credit1 = 0;
            double credit2 = 0;
            double credit3 = 0;
            double credit4 = 0;
            double credit5 = 0;
            double totalCredits = 0;

            bool bAccumulated = this.ckeAccumulated.Checked;
            bool byearly = this.ckeYearly.Checked;
            bool bGraduationPractice = this.ckeGraduationPractice.Checked;
            bool bUseRoom = this.ckeUseRoom.Checked;
            DateTime dte = this.dteDateCreate.DateTime;
            
            try
            {
                credit1 = Convert.ToDouble(this.txtCredits1.Text);
            }
            catch { }
            try
            {
                credit2 = Convert.ToDouble(this.txtCredits2.Text);
            }
            catch { }
            try
            {
                credit3 = Convert.ToDouble(this.txtCredits3.Text);
            }
            catch { }
            try
            {
                credit4 = Convert.ToDouble(this.txtCredits4.Text);
            }
            catch { }
            try
            {
                credit5 = Convert.ToDouble(this.txtCredits5.Text);
            }
            catch { }
            try
            {
                totalCredits = Convert.ToInt16(this.txtTotalCreditsNB.Text);
            }
            catch { }
            
            Training_SubjectInfo subjectInfo = new Training_SubjectInfo(SubjectKey);

            switch (this.m_iAction)
            {
                case ACTION_EDIT:
                    //this.Save(m_bds, m_dbTraining.m_DCSave);
                    if (subjectInfo.Properties.Training_SubjectKey != 0)
                    {
                        //subjectInfo.Properties.ID = subjectID;
                        subjectInfo.Properties.Catalogue_DepartmentKey = departmentKey;
                        subjectInfo.Properties.Name = subjectname;
                        subjectInfo.Properties.Note = subjectNote;
                        subjectInfo.Properties.Credits1 = credit1;
                        subjectInfo.Properties.Credits2 = credit2;
                        subjectInfo.Properties.Credits3 = credit3;
                        subjectInfo.Properties.Credits4 = credit4;
                        subjectInfo.Properties.Credits5 = credit5;
                        subjectInfo.Properties.TotalCredits = totalCredits;
                        subjectInfo.Properties.Accumulated = bAccumulated;
                        subjectInfo.Properties.GraduationPractice = bGraduationPractice;
                        subjectInfo.Properties.Yearly = byearly;
                        subjectInfo.Properties.DateCreate = dte;
                        subjectInfo.Properties.UseRoom = bUseRoom;
                        subjectInfo.Save();
                        this.Validate();
                    }
                    succ = true;
                    break;
                case ACTION_NEW:

                    this.Validate();
                    if (subjectInfo.Properties.Training_SubjectKey != 0)
                    {
                        if (DialogResult.No == XtraMessageBox.Show("Mã môn học đã tồn tại, bạn có muốn tiếp hay không", "Thông báo", MessageBoxButtons.YesNo))
                        {
                            return;
                        }
                    }
                    subjectInfo = new Training_SubjectInfo(-1);
                    subjectInfo.Properties.ID = subjectID;
                    subjectInfo.Properties.Catalogue_DepartmentKey = departmentKey;
                    subjectInfo.Properties.Name = subjectname;
                    subjectInfo.Properties.Note = subjectNote;
                    subjectInfo.Properties.Credits1 = credit1;
                    subjectInfo.Properties.Credits2 = credit2;
                    subjectInfo.Properties.Credits3 = credit3;
                    subjectInfo.Properties.Credits4 = credit4;
                    subjectInfo.Properties.Credits5 = credit5;
                    subjectInfo.Properties.TotalCredits = totalCredits;
                    subjectInfo.Properties.Accumulated = bAccumulated;
                    subjectInfo.Properties.GraduationPractice = bGraduationPractice;
                    subjectInfo.Properties.Yearly = byearly;
                    subjectInfo.Properties.DateCreate = dte;
                    subjectInfo.Properties.UseRoom = bUseRoom;
                    subjectInfo.Save();
                    this.Validate();
                    succ = true;

                    lcgSubject.LoadOneRecord(m_bds);
                    break;
            }
            if (succ)
            {
                Finish();
            }
        }
        private void lueDepartment_EditValueChanged(object sender, EventArgs e)
        {
            GetSubject();
        }

        public void GetSubject()
        {
            if (this.m_iAction == ACTION_NO)
            {
                if (lueCatalogue_DepartmentNB.EditValue != null)
                {
                    m_bds.DataSource = m_dbTraining.m_DCSave.Training_Subjects.GetListByDepartmentKey(lueCatalogue_DepartmentNB.GetIntValue());
                    grcSubject.DataSource = m_bds;
                    lcgSubject.LoadOneRecord(m_bds);

                    if (m_bds.Count > 0)
                    {
                        this.xucBar.DeleteVisible = true;
                        this.xucBar.EditVisible = true;
                    }
                    else
                    {
                        this.xucBar.DeleteVisible = false;
                        this.xucBar.EditVisible = false;
                    }
                }
            }
        }
        private void Edit_AddNew()
        {
            this.txtID.Enabled = true;
            this.txtName.Enabled = true;
            this.txtNote.Enabled = true;

            this.txtCredits1.Enabled = true;
            this.txtCredits2.Enabled = true;
            this.txtCredits3.Enabled = true;
            this.txtCredits4.Enabled = true;
            this.txtCredits5.Enabled = true;

            this.ckeAccumulated.Enabled = true;
            this.ckeGraduationPractice.Enabled = true;
            this.ckeUseRoom.Enabled = true;
            this.ckeYearly.Enabled = true;
            this.dteDateCreate.Enabled = true;

            
            this.xucBar.SaveVisible = true;
            this.xucBar.CancelVisible = true;
            this.xucBar.DeleteVisible = false;
            this.xucBar.AddNewVisible = false;
            this.xucBar.EditVisible = false;
            this.xucBar.ReLoadVisible = false;
            this.groupControl2.Enabled = false;
            this.xucBar.ImportExcelVisible = false;
            this.xucBar.ExportExcelVisible = false;
            this.xucBar.PrintVisible = false;
            if (this.m_iAction == ACTION_NEW)
            {
                this.ckeYearly.Checked = false;
                this.ckeGraduationPractice.Checked = false;
                this.ckeAccumulated.Checked = true;

                this.txtID.Text = "";
                this.txtNote.Text = "";
                this.txtName.Text = "";
                this.txtName.Text = "";
                this.txtCredits1.Text = "0";
                this.txtCredits2.Text = "0";
                this.txtCredits3.Text = "0";
                this.txtCredits4.Text = "0";
                this.txtCredits5.Text = "0";
                this.dteDateCreate.DateTime = SysDateTime.Now;
            }
        }
        private void Finish()
        {
            this.xucBar.ReLoadVisible = true;
            this.txtID.Enabled = false;
            this.txtName.Enabled = false;
            this.txtNote.Enabled = false;
            this.txtCredits1.Enabled = false;
            this.txtCredits2.Enabled = false;
            this.txtCredits3.Enabled = false;
            this.txtCredits4.Enabled = false;
            this.txtCredits5.Enabled = false;
            this.ckeAccumulated.Enabled = false;
            this.ckeGraduationPractice.Enabled = false;
            this.ckeYearly.Enabled = false;
            this.ckeUseRoom.Enabled = false;
            this.dteDateCreate.Enabled = false;
            this.xucBar.SaveVisible = false;
            this.xucBar.CancelVisible = false;
            this.xucBar.CancelVisible = false;
            this.xucBar.SaveVisible = false;
            this.xucBar.DeleteVisible = true;
            this.groupControl2.Enabled = true;
            this.xucBar.SaveVisible = false;
            this.xucBar.EditVisible = true;
            this.xucBar.AddNewVisible = true;
            this.xucBar.ImportExcelVisible = true;
            this.xucBar.ExportExcelVisible = true;
            this.xucBar.PrintVisible = true;
            this.m_iAction = ACTION_NO;

            lcgSubject.LoadOneRecord(m_bds);
        }
        //protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        //{
        //    switch (keyData)
        //    {
        //        case Keys.Control | Keys.S:
        //            if (this.m_iAction == ACTION_EDIT || this.m_iAction == ACTION_NEW)
        //            {
        //                SaveData();
        //                return true;
        //            }
        //            else
        //            {
        //                return false;
        //            }
        //        case Keys.Control | Keys.N:
        //            if (this.m_iAction == ACTION_NO)
        //            {
        //                this.m_iAction = ACTION_NEW;
        //                this.Edit_AddNew();
        //                return true;
        //            }
        //            else
        //            {
        //                return false;
        //            }
        //        case Keys.Escape:
        //            {
        //                if (this.m_iAction == ACTION_NEW || this.m_iAction == ACTION_EDIT)
        //                {
        //                    Finish();
        //                    return true;
        //                }
        //                else
        //                {
        //                    return false;
        //                }
        //            }
        //        case Keys.Control | Keys.E:
        //                {
        //                    if (ACTION_NO == this.m_iAction)
        //                    {
        //                        SaveFileDialog sfd = new SaveFileDialog();
        //                        sfd.Filter = "*.xlsx | *.xls";
        //                        sfd.Title = "Lưu tập tin excel 2007";
        //                        if (sfd.ShowDialog() == DialogResult.OK)
        //                        {
        //                            this.grvSubject.ExportToXlsx(sfd.FileName);
        //                        }
        //                    }
        //                    return false;
        //                }
        //        default:
        //            break;
        //    }

        //    return base.ProcessCmdKey(ref msg, keyData);
        //}

        private void grvSubject_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                int subJectKey = (int)grvSubject.GetFocusedRowCellValue(gclTraining_SubjectKey);
                xucBar.DeleteVisible = true;
                xucBar.EditVisible = true;
            }
            catch
            {
                //int subJectKey = (int)grvSubject.GetFocusedRowCellValue(gclTraining_SubjectKey);
                xucBar.DeleteVisible = false;
                xucBar.EditVisible = false;
            }
        }
        private void SetTotalCredits()
        {
            double totalCredits = 0;
            try
            {
                totalCredits += Convert.ToDouble(this.txtCredits1.Text);
            }
            catch
            {
            }
            try
            {
                totalCredits += Convert.ToDouble(this.txtCredits2.Text);
            }
            catch
            {
            }
            try
            {
                totalCredits += Convert.ToDouble(this.txtCredits3.Text);
            }
            catch
            {
            }

            try
            {
                totalCredits += Convert.ToDouble(this.txtCredits4.Text);
            }
            catch
            {
            }

            try
            {
                totalCredits += Convert.ToDouble(this.txtCredits5.Text);
            }
            catch { }
            this.txtTotalCreditsNB.Text = totalCredits.ToString();
        }

        private void txtCredits1_EditValueChanged(object sender, EventArgs e)
        {
                SetTotalCredits();
        }

        private void txtCredits2_EditValueChanged(object sender, EventArgs e)
        {
                SetTotalCredits();
        }

        private void txtCredits3_EditValueChanged(object sender, EventArgs e)
        {
                SetTotalCredits();
        }

        private void txtCredits4_EditValueChanged(object sender, EventArgs e)
        {
                SetTotalCredits();
        }

        private void txtID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                SetFocusEditer(sender);
            }
        }
        private void SetFocusEditer(object sender)
        {
            TextEdit textEdit = sender as TextEdit;
            int tabIndex = textEdit.TabIndex + 1;
            for (int i = 0; i < layoutControl1.Controls.Count; i++)
            {
                if (layoutControl1.Controls[i].GetType().Name  == "TextEdit")
                {
                    TextEdit text = layoutControl1.Controls[i] as TextEdit;
                    if (text.TabIndex == tabIndex)
                    {
                        text.Focus();
                        text.Select();
                    }
                }
            }
        }

        private void txtName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                SetFocusEditer(sender);
            }
        }

        private void txtCredits1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                SetFocusEditer(sender);
            }
        }

        private void txtCredits2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                SetFocusEditer(sender);
            }
        }

        private void txtCredits3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                SetFocusEditer(sender);
            }
        }

        private void txtCredits4_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                SetFocusEditer(sender);
            }
        }

        private void grvSubject_DoubleClick(object sender, EventArgs e)
        {
                int subjectKey = Convert.ToInt16(this.grvSubject.GetFocusedRowCellValue(gclTraining_SubjectKey).ToString());
                FrmSubjectRelationship frmRelationship = new FrmSubjectRelationship(subjectKey,this.lueCatalogue_DepartmentNB.GetIntValue());
                frmRelationship.ShowDialog();
        }

        private void textEdit1_EditValueChanged(object sender, EventArgs e)
        {
            SetTotalCredits();
        }
    }
}